package com.huawei.bitfun.listener;

import com.huawei.bitfun.ConfigProvider;
import com.huawei.bitfun.Constants;
import com.huawei.bitfun.OptimizeManager;
import com.huawei.bitfun.bean.DocumentBean;
import com.huawei.bitfun.helper.YamlParser;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public final class OptYmlFileListener implements BulkFileListener {
    public OptYmlFileListener() {}

    @Override
    public void after(@NotNull List<? extends @NotNull VFileEvent> events) {
        events.stream()
                .filter(event -> event.getFile() != null)
                .filter(VFilePropertyChangeEvent.class::isInstance)
                .filter(event -> {
                    var file = event.getFile();
                    var path = event.getFile().getCanonicalPath();
                    if (path == null) {
                        return false;
                    }
                    return file.getName().endsWith(Constants.FILE_SUFFIX) && path.contains(Constants.TEMP_DIR_NAME);
                })
                .forEach(event -> {
                    var file = event.getFile();
                    var module = ConfigProvider.getInstance().getModuleModel(file);
                    if (module == null || !module.isNativeModule()) {
                        return;
                    }
                    List<DocumentBean> documentBeans = YamlParser.parserOptYml(file, module);
                    OptimizeManager.getInstance().addAllDocumentBean(documentBeans);
                });
    }
}
